-module(login_block).
-include_lib("nitrogen/include/wf.inc").
-compile(export_all).

						%Builders
assemble_header(X) ->
    X.

assemble_menu(X) ->
    X ++ case hglobals:vget(helper:id_me(), connected) of
	     true ->
		 [#rounded_panel{ color=gray, body=[#link{text="Se déconnnecter", actions=helper:act(?MODULE, {logout, menu}) }] , style="width:100%;"}];
	     _ ->
		 [#rounded_panel{ id = lb_rpanel, color=gray, body=assemble_body([]) ++ [#p{}] ++ register_block:assemble_menu( [] ) , style="width:100%;" }]
	 end.

assemble_body(X) ->
    X ++ [
	  #p{},
	  #label{ text="Nom d'utilisateur : " },
	  #textbox{ id=lb_nick, style="width:100%;" },

	  #p{},
	  #label{ text="Mot de passe : " },
	  #password{ id=lb_pass, style="width: 100%;" },

	  #p{},
	  #checkbox { id=lb_remember_me, text="Rester connecter?", checked=true },

	  #p{},
	  #button{ id=lb_login, text="Connection", actions=helper:act(?MODULE, {login, body} )}
	 ].

						%Wiring

wire() ->
    case hglobals:vget(helper:id_me(), connected) of
	false ->
	    wf:wire(lb_login, lb_nick, #validate {
				validators=[
					    #is_required { text = "X" }
					   ] }),
	    wf:wire(lb_login, lb_pass, #validate {
				validators=[
					    #is_required { text = "X" }
					   ] });
	_ -> ok
    end,
    ok.
						%Behavior
behave({redirect, _}) ->
    wf:redirect("/web/index").
						%Events
event({refresh_panel, menu}) ->
    wf:update(lb_rpanel, assemble_menu( [] ) ),
    ok;

event({login, Where }) -> 
    [Nick] = wf:q(lb_nick),
    [Pass] = wf:q(lb_pass),
    Checked = wf:q(lb_remember_me),
    HashedPass = sha2:hexdigest512(Pass),

    case db:validate_member(name, {Nick, HashedPass}) of
	{true, Status} -> wf:user(Nick),
			  wf:session(hpass, HashedPass),
			  wf:session(status, Status),

			  case Checked of
			      [[111,110]] -> 
				  wf_platform:set_cookie(nick, Nick, "/", 43200),
				  wf_platform:set_cookie(hpass, HashedPass, "/", 43200),
				  wf_platform:set_cookie(status, Status, "/", 43200);
			      _ -> ok
			  end,
			  behave({redirect, Where});
	{false, _} ->
	    wf:flash("Mauvais nom d'utilisateur / mot de passe")
    end;

event({logout, Where}) ->
    wf:clear_session(),
    wf_platform:set_cookie(nick, "", "/", 1),
    wf_platform:set_cookie(hpass, "", "/", 1),
    wf_platform:set_cookie(status, "", "/", 1),
    hglobals:vput(helper:id_me(), connected, false),

    behave({redirect, Where});

event(_) ->
    ok.
